package com.wanli.storemobile.homepage;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wanli.storemobile.R;
import com.wanli.storemobile.base.BaseActivity;
import com.wanli.storemobile.base.DataCallBack;
import com.wanli.storemobile.bean.BaseResponseBean;
import com.wanli.storemobile.bean.BatchAddProductBean;
import com.wanli.storemobile.bean.BatchInStorageBean;
import com.wanli.storemobile.bean.ProductListBean;
import com.wanli.storemobile.event.ProductEvent;
import com.wanli.storemobile.homepage.adapter.BatchInStorageAdapter;
import com.wanli.storemobile.homepage.model.HomePageModelImpl;
import com.wanli.storemobile.homepage.model.IHomePageModel;
import com.wanli.storemobile.utils.ToastUtil;
import com.wanli.storemobile.widget.AppTitleBar;
import com.wanli.storemobile.widget.ViewLoading;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.common.Constant;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BatchInStorageActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_new_add)
    TextView tvNewAdd;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    private BatchInStorageAdapter listAdapter;
    private List<BatchInStorageBean> beanList;
    private IHomePageModel homePageModel;
    private BatchInStorageBean batchInStorageBean;
    private List<ProductListBean.DataBean.ItemListBean> beanListIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_batch_in_storage);
        ButterKnife.bind(this);
        initView();
        requestGoodsIndex();
    }

    public void initView() {
        beanListIndex = new ArrayList<>();
        homePageModel = new HomePageModelImpl();
        beanList = new ArrayList<>();
        beanList.add(new BatchInStorageBean());
        listAdapter = new BatchInStorageAdapter(beanList);
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerView.setAdapter(listAdapter);
        listAdapter.setOnCallBackListener(new BatchInStorageAdapter.onCallBackListener() {
            @Override
            public void onCallBack(int type, int position) {
                // 2删除  3扫码
                if (type == 2) {
                    beanList.remove(position);
                    listAdapter.notifyDataSetChanged();
                } else if (type == 3) {
                    batchInStorageBean = beanList.get(position);
                    //扫一扫
                    scanCode();
                }
            }
        });
    }

    private void requestGoodsIndex() {
        homePageModel.requestGoodsIndex(1, "", "", new DataCallBack<ProductListBean>() {
            @Override
            public void onSuccessful(ProductListBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    beanListIndex.addAll(bean.getData().getItemList());
                }
            }

            @Override
            public void onFailed(String msg, String code) {
            }
        });
    }

    /**
     * 批量入库
     */
    public void requestGoodsBatchAdd() {
        ViewLoading.showProgress(mActivity, "提交中......");
        homePageModel.requestGoodsInStorage(beanList, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                EventBus.getDefault().post(new ProductEvent());
                ToastUtil.showShort(bean.getMsg());
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @OnClick({R.id.tv_new_add, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_new_add:
                beanList.add(new BatchInStorageBean());
                listAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_commit:
                if (beanList.size() == 0) {
                    ToastUtil.showShort("请添加商品");
                }
                requestGoodsBatchAdd();
                break;
        }
    }

    private int REQUEST_CODE_SCAN = 111;//扫一扫请求状态码

    public void scanCode() {
        AndPermission.with(this)
                .runtime()
                .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Intent intent = new Intent(BatchInStorageActivity.this, CaptureActivity.class);
                        startActivityForResult(intent, REQUEST_CODE_SCAN);
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {
                        Uri packageURI = Uri.parse("package:" + Objects.requireNonNull(BatchInStorageActivity.this).getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        Toast.makeText(BatchInStorageActivity.this, "没有权限无法扫描呦", Toast.LENGTH_LONG).show();
                    }
                })
                .start();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
//                Log.e(TAG, "扫码返回: " + content);
                ProductListBean.DataBean.ItemListBean itemList = null;
                for (ProductListBean.DataBean.ItemListBean itemListBean : beanListIndex) {
                    if (itemListBean.getCode().equals(content)) {
                        itemList = itemListBean;
                        break;
                    }
                }

                if (itemList != null) {
                    batchInStorageBean.setCode(content);
                    batchInStorageBean.setName(itemList.getName());
                    batchInStorageBean.setCount((batchInStorageBean.getCount() + 1));
                    batchInStorageBean.setId(itemList.getId() + "");
                    batchInStorageBean.setThumb(itemList.getThumb());
                    listAdapter.notifyDataSetChanged();
                } else {
                    ToastUtil.showShort("未找到商品");
                }
            }
        }
    }

}
